import 'dart:async';
import 'dart:ui';
import 'package:flutter/widgets.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:get_storage/get_storage.dart';
import 'package:grab_the_order/app/data/models/log_model.dart';
import 'package:grab_the_order/app/data/services/log_service.dart';
import 'package:grab_the_order/app/data/services/rule_service.dart';
import 'package:grab_the_order/app/modules/rule_model.dart';

// 全局函数，用于初始化后台服务
Future<void> initializeBackgroundService() async {
  final service = FlutterBackgroundService();

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      isForegroundMode: true,
      autoStart: false,
      notificationChannelId: 'grab_order_channel',
      initialNotificationTitle: '抢单助手',
      initialNotificationContent: '服务初始化',
      foregroundServiceNotificationId: 888,
    ),
    iosConfiguration: IosConfiguration(
      autoStart: false,
      onForeground: onStart,
      onBackground: onIosBackground, // 【已修正】确保函数存在
    ),
  );
}

// 【已修正】添加缺失的 onIosBackground 函数定义
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();
  // iOS后台功能受限，这里只是一个占位符
  return true;
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();
  await GetStorage.init();
  final ruleService = RuleService();
  final logService = LogService();
  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });
    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stop_service').listen((event) {
    service.stopSelf();
  });

  // 【核心】服务启动后，立即设为前台并更新通知
  if (service is AndroidServiceInstance) {
    if (await service.isForegroundService()) {
      await service.setForegroundNotificationInfo(
        title: "抢单助手",
        content: "服务运行中...",
      );
    }
  }

  print("后台抢单服务已启动！");

  logService.addLog("后台服务已启动。", level: LogLevel.success);

  service.on('onOrderDetected').listen((event) {
    if (event == null) return;
    logService.addLog("检测到订单数据: $event");

    final targetApp = TargetApp.didi;
    final bool isMatch = ruleService.evaluate(event, targetApp);

    if (isMatch) {
      logService.addLog("规则匹配成功，执行操作。", level: LogLevel.success);
      service.invoke('update_ui', {'orders_grabbed': 1});
    } else {
      logService.addLog("规则不匹配，已忽略。", level: LogLevel.warning);
    }
  });

  Timer? timer;
  if (service is AndroidServiceInstance) {
    int secondsElapsed = 0;
    // 立即发送一次启动信号
    service.invoke('running', {'duration': "00:00:00"});

    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      secondsElapsed++;
      final Duration duration = Duration(seconds: secondsElapsed);
      final String formattedDuration =
          "${duration.inHours.toString().padLeft(2, '0')}:"
          "${(duration.inMinutes % 60).toString().padLeft(2, '0')}:"
          "${(duration.inSeconds % 60).toString().padLeft(2, '0')}";

      // 通过 'running' 事件持续发送状态和数据
      service.invoke('running', {'duration': formattedDuration});
    });
  }

  service.on('stop').listen((event) {
    timer?.cancel();
    logService.addLog("后台服务已停止。", level: LogLevel.info);
    // 发送停止信号
    service.invoke('stopped');
    print("后台抢单服务已停止！");
  });
}
